package com.scx.bizmq;

import com.rabbitmq.client.Channel;
import com.scx.constant.ChartConstant;
import com.scx.entity.Chart;
import com.scx.service.ChartService;
import com.scx.utils.AiUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
class BiMessageConsumer {
    @Resource
    private ChartService chartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "chart.queue"),
            exchange = @Exchange(name = "chart.exchange",type = ExchangeTypes.DIRECT),
            key = {"chartByAi"}
    ),ackMode = "MANUAL")
    public void receiveMessage(Map<String,Object> message, Channel channel , @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        log.info("接收到消息：{}",message);
        if(ObjectUtils.isEmpty(message)){
            //拒绝消息
            channel.basicNack(tag,false,false);
            throw new RuntimeException("消息为空");
        }

        //解析消息
        Long chartId = (Long) message.get("chartId");
        String userInput = (String) message.get("userInput");

        //更改状态为执行中
        Chart updateRunning = new Chart();
        updateRunning.setId(chartId);
        updateRunning.setStatus(ChartConstant.RUNNING);
        boolean b = chartService.updateById(updateRunning);
        if(!b){
            channel.basicNack(tag,false,false);
            chartService.handleChartUpdateError(chartId,"更新图表运行中状态时失败");
            return;
        }

        //调用AI
        String result = AiUtils.doChat(userInput.toString());
        if(StringUtils.isBlank(result)){
            channel.basicNack(tag,false,false);
            chartService.handleChartUpdateError(chartId,"AI生成错误");
            return;
        }
        String[] parts = result.split("```json\n");
        // 提取代码部分
        String code = parts[1].split("```")[0].trim();
        // 提取结论部分
        String conclusion = result.split("```")[2].trim();

        //更新状态为已完成
        Chart updateSucceed = new Chart();
        updateSucceed.setId(chartId);
        updateSucceed.setGenChart(code);
        updateSucceed.setGenResult(conclusion);
        updateSucceed.setStatus(ChartConstant.SUCCEED);
        boolean b1 = chartService.updateById(updateSucceed);
        if(!b1){
            channel.basicNack(tag,false,false);
            chartService.handleChartUpdateError(chartId,"更新图表成功状态时失败");
        }

        //确认消息
        channel.basicAck(tag,false);
    }
}
